package Generic;

import evolution_superclasses.Phenotype;
import evolution_superclasses.Selection_Protocol;

public class Generic_Selection_Protocol extends Selection_Protocol {

	public Generic_Selection_Protocol(int nr, int poolSize) {
		super(nr, poolSize);
	}

	@Override
	protected void fullGenerationReplacement(Phenotype[] younglings) {
		set_adultPool(younglings);
	}

	@Override
	protected void overproduction(Phenotype[] younglings) {
		if(younglings.length == get_poolSize()){
			fullGenerationReplacement(younglings);
			return;
		}
		
		//Assume youglings are sorted, take N most fit.
		Phenotype[] tmpPool = new Phenotype[get_poolSize()];
		for(int i = 0; i < get_poolSize(); i++)
			tmpPool[i] = younglings[i];
		set_adultPool(tmpPool);
	}

	@Override
	protected void generationMixing(Phenotype[] younglings) {
		if(get_adultPool()[0] == null){
			overproduction(younglings);
			return;
		}
		
		//Assume youglings are sorted, take N most fit form younglings and existing pool combined.
		Phenotype[] tmpPool = new Phenotype[get_poolSize()];
		Phenotype bestOld, bestNew;
		int oldI = 0, newI = 0;
		for(int i = 0; i < get_poolSize(); i++){
			bestOld = _adultPool[oldI];
			bestNew = younglings[newI];
			if(bestOld.get_fitness() > bestNew.get_fitness()){
				tmpPool[i] = bestOld;
				oldI++;
			}else{
				tmpPool[i] = bestNew;
				newI++;
			}
		}
		set_adultPool(tmpPool);
	}

}
